# -*- encoding:utf-8 -*-
import random

# from flask import Flask
import time

import datetime
from json import JSONDecodeError

from commons import *
from constants import *


# app = Flask(__name__)

# @app.route("/smp/horseman/login")
def member_login():
    url = member_url + "member/userLogin/login"
    data = {"loginAccount": "17629262609", "password": "88316675D7882E3FDBE066000273842C", "loginType": "1"}
    return getPost(url, None, data)


def imm_handler(token):
    url = member_url + "member/placeOrder/immHandle"
    data = {"memo": "测试数据" + str(int(time.time())), "taskType": "2", "taskName": "帮我送", "budgetAmount": 750,
            "budgetDistance": 6.7,
            "estimatedServiceTime": 67, "senderAddress": "测试数据" + str(int(time.time())) + "陕西省西安市雁塔区西安软件新城国家电子商务示范基地A3-2", "senderName": "高竞",
            "senderTel": "17629262609", "startLng": 108.839461, "startLat": 34.207934,
            "receiverAddress": "测试数据" + str(int(time.time())) + "陕西省西安市雁塔区龙城铭园2期16号楼3单元", "receiverName": "高竞6", "receiverTel": "17629262609",
            "termLng": 108.871402, "termLat": 34.226922, "goodsTypeName": "文件", "goodsType": "999999966",
            "basePrice": 550, "distancePrice": 200, "goodsWeight": 1, "isImmediate": 1,
            "pickupTime": time.strftime("%Y-%m-%d %H:%M", time.localtime()), "pickupTag": 1}
    return getPost(url, token, data)


def query_order_pay(token, id):
    url = member_url + "member/placeOrder/queryOrderPay?id=" + str(id)
    return getPost(url, token, None)


def imm_pay(token, order_pay_result):
    url = member_url + "member/placeOrder/immPay"
    data = {"budgetAmount": 550, "couponCode": "", "discountAmount": 0, "payAmount": 550,
            "taskCode": "02520448066151514503768", "returnUrl": "http://member.web.ng.scare.ml/#/payResult",
            "payType": "4"}
    data['taskCode'] = order_pay_result['data']['taskCode']
    data['budgetAmount'] = order_pay_result['data']['budgetAmount']
    data['payAmount'] = order_pay_result['data']['payAmount']
    return getPost(url, token, data)

def payment_result(token, pay_result):
    url = member_url + "member/placeOrder/paymentResultNotify"
    data = {
              "orderCode": "03010100339936250652032",
              "payResult": 1,
              "payCode": "02810077549418199821859"
            }
    data['orderCode'] = pay_result['data']['orderCode']
    data['payCode'] = pay_result['data']['signData'].split(":")[-1].replace("\"", "").replace("}", "")
    return getPost(url, token, data)

def order():
    try:
        data = member_login()
        token = data['data']['token']
        handler_result = imm_handler(token)
        task_id = handler_result['data']['taskId']
        order_pay_result = query_order_pay(token, task_id)
        pay_result = imm_pay(token, order_pay_result)
        payed_result = payment_result(token, pay_result)
        print(("结果: %s, taskCode: %s, orderCode: %s, payCode: %s, account: %s") %
              (pay_result, order_pay_result['data']['taskCode'], pay_result['data']['orderCode'], pay_result['data']['signData'].split(":")[-1].replace("\"", "").replace("}", ""), data['data']['loginAccountCode']))
        pass
    except (RuntimeError, TypeError, NameError, JSONDecodeError):
        print("内部异常，请检查服务连通")
        return None


if __name__ == '__main__':
    count = 0
    while True:
        order()
        count += 1
        if count >= 2:
            break
        pass
    pass
